# -*- coding: utf-8 -*-

from HuobiDMService import HuobiDM
import datetime
import time

URL = 'https://api.hbdm.com'
ACCESS_KEY = '854b2622-bgbfh5tv3f-89ac054f-5d979'
SECRET_KEY = '9055920b-b55bd08c-fe9d7353-c3894'
dm = HuobiDM(URL, ACCESS_KEY, SECRET_KEY)


def yicang(p1,p2,diff,amount,direction,rate):
    symbol = p1[:3]
    dit ={'CW':'this_week','NW':'next_week','CQ':'quarter','NQ':'next_quarter'}
    while True:
        a = dm.get_contract_depth(p1, 'step6')
        b = dm.get_contract_depth(p2, 'step6')
        a1 = b.get('tick').get('asks')[0][0]  #远月卖一
        a2 = a.get('tick').get('bids')[0][0]   #近月买一
        a3 = b.get('tick').get('bids')[0][0]   #远月买一
        a4 = a.get('tick').get('asks')[0][0]   #近月卖一
        dif = a1-a2
        dif1 = a3-a4
        number = 0
        number1 = 0
        n = int(amount/10) 
        if dif < diff and number<=n and direction=='buy':
            orders_data = {'orders_data': [
                   {'symbol': symbol, 'contract_type': dit.get(p2[-2:]),  
                    'volume':10, 'direction':'buy', 'offset':'open', 
                    'leverRate':rate, 'orderPriceType':'optimal_5'},
                   {'symbol': symbol,'contract_type': dit.get(p1[-2:]), 
                    'volume':10, 'direction':'buy', 'offset':'close', 
                    'leverRate':rate, 'orderPriceType':'optimal_5'}]} 
            dm.send_contract_batchorder(orders_data)
            number += 1
        if dif1 > diff and  number1 <=n and direction=='sell':
            orders_data = {'orders_data': [
                   {'symbol': symbol, 'contract_type': dit.get(p2[-2:]),  
                    'volume':10, 'direction':'sell', 'offset':'open', 
                    'leverRate':rate, 'orderPriceType':'optimal_5'},
                   {'symbol': symbol,'contract_type': dit.get(p1[-2:]), 
                    'volume':10, 'direction':'sell', 'offset':'close', 
                    'leverRate':rate, 'orderPriceType':'optimal_5'}]} 
            dm.send_contract_batchorder(orders_data)
            number1 += 1
        if number==n or number1==n:
            print('移仓已经结束')
            break
        time.sleep(5)
        
yicang('BTC_CW','BTC_NW',3,200,'buy',50)
    